package brc.syntacticTree;

import java.io.IOException;
import java.io.Writer;

import brc.symbolTable.LabelMaker;

public class UnaryBooleanExprNode extends BooleanExprNode {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2077530483482751411L;
	private TypedTreeNode left;
	private TypedTreeNode right;
	private Comparison comparison;
	
	public UnaryBooleanExprNode(TypedTreeNode left, TypedTreeNode right, Comparison comparison) {
		if (left == null || right == null || comparison == null) {
			throw new NullPointerException("Left and right members and comparison types must be known");
		}
		this.left = left;
		this.right = right;
		this.comparison = comparison;
	}

	public TypedTreeNode getLeft() {
		return this.left;
	}
	public TypedTreeNode getRight() {
		return this.right;
	}
	public Comparison getComparison() {
		return this.comparison;
	}

	@Override
	public void writeAssembly(Writer writer) throws IOException {
		// coloca os elementos na stack
		this.left.writeAssembly(writer);
		this.right.writeAssembly(writer);
		
		String labelSucessful = LabelMaker.next("unaryBoolSucess");
		String labelEnd = LabelMaker.next("unaryBoolEnd");
		
		// subtrai eles
		writer.write("isub\r\n");
		
		switch (this.comparison) {
		case Equals:
			writer.write("ifeq " + labelSucessful + "\r\n");
			break;
		case Greater:
			writer.write("ifgt " + labelSucessful + "\r\n");
			break;
		case GreaterOrEquals:
			writer.write("ifge " + labelSucessful + "\r\n");
			break;
		case Lesser:
			writer.write("iflt " + labelSucessful + "\r\n");
			break;
		case LesserOrEquals:
			writer.write("ifle " + labelSucessful + "\r\n");
			break;
		case NotEquals:
			writer.write("ifne " + labelSucessful + "\r\n");
			break;
		}
		writer.write("ldc 0\r\n"); // true
		writer.write("goto " + labelEnd + "\r\n");
		writer.write(labelSucessful + ":\r\n");		
		writer.write("ldc 1\r\n"); // false
		writer.write(labelEnd + ":\r\n");
	}

	@Override
	public void semanticCheck() throws SemanticException {
		this.getLeft().semanticCheck();
		this.getRight().semanticCheck();

		if (this.left.getType() != TypedTreeNode.TIPO_NUMERO || this.right.getType() != TypedTreeNode.TIPO_NUMERO) {
			throw new SemanticException("Comparision operations can be done for numbers");
		}
	}

	public enum Comparison {
		Greater,
		Lesser,
		GreaterOrEquals,
		LesserOrEquals,
		Equals,
		NotEquals
	}
}
